Page({
    data: {
        bookId: '',
        book: {
            brief: '暂无'
        },
        isExpanded: false,
        isCollected: false,
        brief1: '',
        inventoryList: [],
        callNumber: '',
        bookCoverUrl : 'https://ov-library-1316830564.cos.ap-guangzhou.myqcloud.com/bookCover%2F',
        defaultCover : '/resource/images/defaultCover.png'
    },

    onLoad(options) {
        if (options.id) {
            this.setData({
                bookId: options.id
            });
            this.fetchBookDetail(options.id);
        }
        let that = this
        let bookId = this.data.bookId
        let favorites = wx.getStorageSync('favorites') || [];
        const index = favorites.findIndex(id => id === bookId);
        if (index !== -1) {
            this.setData({
                isCollected: true
            })
        }

        this.queryInventory();
        this.queryCallNumber();
    },

    fetchBookDetail(bookId) {
        wx.request({
            url: `http://localhost:8080/books/query/${bookId}`,
            method: "GET",
            success: (res) => {
                let brief2 = ''
                if (res.data.data.brief) {
                    brief2 = res.data.data.brief.slice(0, 100)
                }
                this.setData({
                    book: res.data.data,
                    brief1: brief2
                });
            }
        });
    },

    toggleExpand() {
        this.setData({
            isExpanded: !this.data.isExpanded
        });
    },

    // toggleCollect() {
    //     this.setData({
    //         isCollected: !this.data.isCollected
    //     });
    //     wx.showToast({
    //         title: this.data.isCollected ? "已收藏" : "已取消收藏",
    //         icon: "success"
    //     });
    // },

    toggleFavorite() {
        let that = this
        let bookId = this.data.bookId
        let favorites = wx.getStorageSync('favorites') || [];
        const index = favorites.findIndex(id => id === bookId);
        if (index !== -1) {
            // 已收藏 → 执行移除
            favorites.splice(index, 1);
            wx.setStorageSync('favorites', favorites);
            this.setData({
                isCollected: false
            })
            wx.showToast({
                title: this.data.isCollected ? "已收藏" : "已取消收藏",
                icon: "success"
            });
            return {
                success: true,
                action: 'removed'
            }; // 返回操作类型
        } else {
            // 未收藏 → 尝试添加
            if (favorites.length >= 50) {
                wx.showToast({
                    title: '最多收藏50本',
                    icon: 'none'
                });
                return {
                    success: false,
                    action: 'add'
                }; // 添加失败
            }
            favorites.push(bookId);
            wx.setStorageSync('favorites', favorites);
            this.setData({
                isCollected: true
            })
            wx.showToast({
                title: this.data.isCollected ? "已收藏" : "已取消收藏",
                icon: "success"
            });
            return {
                success: true,
                action: 'added'
            }; // 返回操作类型
        }
    },

    //通过bookId获取库存信息
    queryInventory() {
        let that = this
        let bookId = this.data.bookId
        wx.request({
            url: `http://localhost:8080/inventory/queryByBookId/${bookId}`,
            method: "GET",
            success: (res) => {
                if (res.data.data.length > 0) {
                    // 处理库存信息
                    that.setData({
                        inventoryList: res.data.data
                        
                    });
                    that.queryBranchName()

                } else {
                    // wx.showToast({
                    //     title: '库存不存在',
                    //     icon: 'none'
                    // });
                    that.setData({
                        inventoryList: ''
                    });
                }
            },
            fail: (err) => {
                wx.showToast({
                    title: '查询失败，请重试',
                    icon: 'none'
                });
            }
        })
    },

    //遍历inventoryList，并通过branchId查询branchName
    queryBranchName() {
        let that = this
        let inventoryList = this.data.inventoryList
        let branchNameList = []
        let completedRequests = 0; // 用于跟踪完成的请求数量
        for (let i = 0; i < inventoryList.length; i++) {
            let branchId = inventoryList[i].branchId
            wx.request({
                url: `http://localhost:8080/branch/query/${branchId}`,
                method: "GET",
                success: (res) => {
                    branchNameList.push(res.data.data.branchName);
                    completedRequests++; // 递增完成的请求数量

                    // 所有请求完成后，合并数据并更新页面
                    if (completedRequests === inventoryList.length) {
                        let mergedList = inventoryList.map((item, index) => {
                            return {
                                ...item,
                                branchName: branchNameList[index]
                            };
                        });
                        that.setData({
                            inventoryList: mergedList
                        });
                    }
    
                    console.log("branchNameList:" + branchNameList)
                },
            })
        }
    },

    //通过bookId获取callNumber
    queryCallNumber() {
        let that = this
        let bookId = this.data.bookId
        wx.request({
            url: `http://localhost:8080/books/query/${bookId}`,
            method: "GET",
            success: (res) => {
                this.setData({
                    callNumber: res.data.data.callNumber
                });
            }
        })
    },

    borrowing: function (event) {
        // debugger
        const item = event.currentTarget.dataset.item; // 获取当前书籍数据
        const inventoryId = item.inventoryId; // 假设 item 包含 inventoryId 字段
        const changeAmount = -1; // 每次借书减少1本可借数量
        // 调用后端接口
        wx.request({
          url: 'http://localhost:8080/inventory/updateAndAddRecord?inventoryId=' + inventoryId + "&availableCount=" + changeAmount+ "&userId=" + wx.getStorageSync('userId'),
          method: 'PUT',
          success: (res) => {
            if (res.data.code === 0) { // 根据你的后端返回结构判断成功
              // 更新前端数据
              const updatedList = this.data.inventoryList.map(inv => {
                if (inv.inventoryId === inventoryId) {
                  inv.availableCount += changeAmount; // 更新可借数量
                }
                return inv;
              });
              this.setData({ inventoryList: updatedList });
              wx.showToast({ title: '借书成功', icon: 'success' });
            } else {
              wx.showToast({ title: res.data.msg || '操作失败', icon: 'none' });
            }
          },
          fail: () => {
            wx.showToast({ title: '网络错误', icon: 'none' });
          }
        });
      }

});